package com.example.paging.repository

import androidx.lifecycle.liveData
import androidx.paging.Pager
import androidx.paging.PagingConfig
import com.example.paging.network.ArticleNetwork
import com.example.paging.ui.HomePageSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlin.coroutines.CoroutineContext

object ArticleRepository {

    fun getHomeVo(page: Int) = fire(Dispatchers.IO) {
        coroutineScope {
            val deferredHomeVO = async {
                ArticleNetwork.getHomeVo(page)
            }
            val homeVOResponse = deferredHomeVO.await()
            if (homeVOResponse.errorCode == 0) {
                Result.success(homeVOResponse)
            } else {
                Result.failure(
                    RuntimeException(homeVOResponse.errorMsg)
                )
            }
        }
    }

    fun getArticleData() = Pager(PagingConfig(pageSize = 20)){
        HomePageSource()
    }.flow



    private fun <T> fire(context: CoroutineContext, block: suspend () -> Result<T>) =
        liveData<Result<T>>(context) {
            val result = try {
                block()
            } catch (e: Exception) {
                Result.failure<T>(e)
            }
            emit(result)
        }

}